package com.tracesystem.service.impl;

import com.tracesystem.commons.Result;
import com.tracesystem.controller.info.FileUploadInfo;
import com.tracesystem.model.IssueAttach;
import com.tracesystem.dao.IssueAttachDao;
import com.tracesystem.service.IssueAttachService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tracesystem.util.CommonsUtils;
import com.tracesystem.util.OSSTemplate;
import com.tracesystem.util.exception.AttachNotFoundException;
import com.tracesystem.util.exception.code.IssueAttachExceptionCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;

/**
 * <p>
 *  附件业务类
 * </p>
 *
 * @author Kevin Martin
 * @since 2022-03-23
 */
@Service
@Transactional
public class IssueAttachServiceImpl extends ServiceImpl<IssueAttachDao, IssueAttach> implements IssueAttachService {

    @Autowired
    private OSSTemplate ossTemplate;
    /*
     * @Description:文件上传 添加附件信息
     **/
    @Override
    public Result<FileUploadInfo> uploadFile(MultipartFile file) {
        String fileName = "ts"+System.currentTimeMillis();
        String fileUrl = "";
        try {
            fileUrl = ossTemplate.uploadFile(fileName, file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileUploadInfo fileUploadInfo = new FileUploadInfo();
        String name = file.getOriginalFilename();
        String type = name.substring(name.lastIndexOf(".")+1);
        fileUploadInfo.setFileUrl(fileUrl);
        fileUploadInfo.setAttachFile(name);
        fileUploadInfo.setFileSize(new BigDecimal(file.getSize()));
        fileUploadInfo.setMimeType(type);
        fileUploadInfo.setIsPic(type.equalsIgnoreCase("jpg")||type.equalsIgnoreCase("png")?1:0);
        fileUploadInfo.setLogState("正常");
        return Result.getInstance(FileUploadInfo.class).setMsg("上传成功").setData(fileUploadInfo);
    }
    /*
     * @Description:附件下载
     **/
    @Override
    public Result downloadFile(Integer attachId) {
        IssueAttach issueAttach = baseMapper.selectById(attachId);
        if (null == issueAttach){
            throw new AttachNotFoundException(IssueAttachExceptionCode.ATTACH_NOT_FOUND_EXCEPTION);
        }
        ossTemplate.download(issueAttach.getFileUrl(),issueAttach.getAttachFile());
        return Result.getInstance().setMsg("下载成功！");
    }
}
